package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	public static void main(String args[]) throws Exception {
		try {
			testClient();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//	    // 要连接的服务端IP地址和端口
//	    String host = "127.0.0.1";
//	    int port = 12345;
//	    // 与服务端建立连接
//	    System.out.println("====== Client客户端已经获取socket =======\n");
//	    Socket socket = new Socket(host, port);
//	    // 建立连接后获得输出流
//	    System.out.println("====== Client客户端正在发送数据 =======\n");
//	    OutputStream outputStream = socket.getOutputStream();
//	    String message = "你好abc123！#@￥@%（）@#》？";
//	    socket.getOutputStream().write(message.getBytes("UTF-8"));
//	    //通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
//	    socket.shutdownOutput();
//	    System.out.println("====== Client客户端发送完成=======\n");
//	    
//	    System.out.println("====== Client客户端正在接收数据 =======\n");
//	    InputStream inputStream = socket.getInputStream();
//	    byte[] bytes = new byte[1024];
//	    int len;
//	    StringBuilder sb = new StringBuilder();
//	    while ((len = inputStream.read(bytes)) != -1) {
//	      //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
//	      sb.append(new String(bytes, 0, len,"UTF-8"));
//	    }
//	    System.out.println("====== Client客户端接收完成 =======\n");
//	    System.out.println("get message from server: " + sb);
//	    
//	    
//	    System.out.println("====== Client客户端即将断开socket =======\n");
//	    inputStream.close();
//	    outputStream.close();
//	    socket.close();
	  }

	
	public static void testClient() throws UnknownHostException, IOException {
		int port = 12345;
		String ipAddress = "localhost";
		Socket so = new Socket(ipAddress, port);
		so.setSoTimeout(1000); // 3s
		// check socket status
		// socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()&& !socket.isInputShutdown() && !socket.isOutputShutdown()
		// socket.sendUrgentData(0); // 发送紧急数据，检验连接是否断开，也可使用心跳包的方式
	    // 建立连接后获得输出流
	    System.out.println("====== Client客户端正在发送数据 =======\n");
	    String message = "你好abc123！#@￥@%（）@#》？";
	    so.getOutputStream().write(message.getBytes("UTF-8"));
	    //通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
	    so.shutdownOutput();


	    InputStream inputStream = so.getInputStream();
	    byte[] bytes = new byte[1024];
	    int len;
	    StringBuilder sb = new StringBuilder();
	    while ((len = inputStream.read(bytes)) != -1) {
	      //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
	      sb.append(new String(bytes, 0, len,"UTF-8"));
	    }
	    so.shutdownInput();
	    System.out.println("====== Client客户端接收完成 =======\n");
	    System.out.println(sb);
	    
	    
	    
//	    inputStream.close(); // 如果关闭了输出流，那么相应的Socket也将关闭，和直接关闭Socket一个性质\
	    so.close();
	    System.out.println("====== Client客户端断开socket =======\n");
	}
}
